package com.forum.service.impl;

import com.forum.constant.MessageConstant;
import com.forum.constant.StatusConstant;
import com.forum.constant.TypeConstant;
import com.forum.context.BaseContext;
import com.forum.dto.ThreadUpdateDTO;
import com.forum.dto.ThreadsDTO;
import com.forum.dto.ThreadsPageQueryDTO;
import com.forum.entity.Images;
import com.forum.entity.Threads;
import com.forum.exception.LockedNotDisableException;
import com.forum.exception.ReasonNotNullException;
import com.forum.mapper.ThreadsMapper;
import com.forum.mapper.ImagesMapper;
import com.forum.mapper.UserMapper;
import com.forum.result.PageResult;
import com.forum.service.ThreadsService;
import com.forum.vo.*;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Slf4j
@Service
public class ThreadsServiceImpl implements ThreadsService {
    @Autowired
    private ThreadsMapper threadsMapper;

    @Autowired
    private ImagesMapper imagesMapper;
    @Autowired
    private UserMapper userMapper;
    @Override
    public PageResult pageQuery(ThreadsPageQueryDTO threadsPageQueryDTO) {
        PageHelper.startPage(threadsPageQueryDTO.getPage(),threadsPageQueryDTO.getPageSize());
        Page<Threads> page = threadsMapper.pageQuery(threadsPageQueryDTO);
        long total = page.getTotal();
        List<Threads> result = page.getResult();
        return new PageResult(total, result);

    }

    @Override
    public void updateByIdIsSticky(Long id, Integer isSticky) {
        threadsMapper.updateByIdIsSticky(id, isSticky);
    }

    @Override
    public void deleteById(Long id) {
        Threads threads= threadsMapper.queryById(id);
        log.info("threads查询出来的数据,{}",threads);
        if (threads.getIsLocked() == StatusConstant.DISABLE){
            throw new LockedNotDisableException(MessageConstant.LOCKED_SEAL);
        }
        threadsMapper.deleteById(id);
    }

    @Override
    public void updateByIdIsLocked(ThreadUpdateDTO threadUpdateDTO) {
        if (threadUpdateDTO.getIsLocked() == 1 && threadUpdateDTO.getReason() == null){
            throw new  ReasonNotNullException(MessageConstant.REASON_NOT_NULL);
        }
        threadsMapper.updateByIdIsLocked(threadUpdateDTO);
    }

    /**
     * 发布帖子
     * @param threadsDTO
     */
    @Override
    @Transactional
    public void publish(ThreadsDTO threadsDTO) {
        Long userId = BaseContext.getCurrentId();
//        log.info("用户id{}",userId);
        Threads threads = new Threads();
        BeanUtils.copyProperties(threadsDTO,threads);
        threads.setUserId(userId);
        log.info("添加的值，{}",threads);
        threadsMapper.publish(threads);
        Long id = threads.getId();

        List<Images> imageList = threadsDTO.getImageList();
        if (imageList != null && imageList.size() > 0){
            imageList.forEach(images -> {
                images.setThreadId(id);
            });
            log.info("图片列表{}",imageList);
            imagesMapper.insertBatch(imageList);
        }
    }

    @Override
    @Transactional

    public List<ThreadsVO> ArticleList() {
        Integer type = TypeConstant.ARTICLE;
        List<ThreadsVO> threadsVOS = threadsMapper.queryTop3(type);
        if (threadsVOS == null) {
            return null;
        }
        List<ThreadsVO> list = threadsVOS.stream().map(threads -> {
            ThreadsVO threadsVO = new ThreadsVO();
            BeanUtils.copyProperties(threads, threadsVO);
            Long userId = threads.getUserId();
            UserInfoVO userInfoVO = userMapper.getUserInfoById(userId);
            BeanUtils.copyProperties(userInfoVO, threadsVO);
            return threadsVO;
        }).toList();
        return list;
    }


        @Override
        @Transactional
        public List<TopicsVO> TopicList() {
            Integer type = TypeConstant.TOPIC;
            List<Threads> threads = threadsMapper.queryTop4(type);
            if (threads == null) {
                return null;
            }
            List<TopicsVO> list = threads.stream().map(thread -> {
                TopicsVO topicsVO = new TopicsVO(); // 每次创建新实例
                BeanUtils.copyProperties(thread, topicsVO);

                Long threadId = thread.getId();
                List<Images> images = imagesMapper.queryByThreadId(threadId);
                topicsVO.setImageList(images);

                UserInfoVO userInfoVO = userMapper.getUserInfoById(thread.getUserId());
                BeanUtils.copyProperties(userInfoVO, topicsVO);
                return topicsVO;
            }).toList();
            return list;
        }

    @Override
    @Transactional
    public List<ClassicArticlesTop3VO> articleTop3() {
        Integer type = TypeConstant.ARTICLE;
        List<Threads> threads = threadsMapper.queryArticleTop3(type);
        if (threads == null) {
            return null;
        }
        List<ClassicArticlesTop3VO> list = threads.stream().map(thread -> {
            ClassicArticlesTop3VO articlesTop3VO = new ClassicArticlesTop3VO(); // 每次创建新实例
            BeanUtils.copyProperties(thread, articlesTop3VO);

            Long threadId = thread.getId();
            String images = imagesMapper.queryByIdImage(threadId);
            articlesTop3VO.setImage(images);

            UserInfoVO userInfoVO = userMapper.getUserInfoById(thread.getUserId());
            BeanUtils.copyProperties(userInfoVO, articlesTop3VO);
            return articlesTop3VO;
        }).toList();

        return list;
    }


    @Override
    @Transactional
    public List<ArticlesAndTopicsVO> ArticlesAndTopics(Long categoryId, Integer type) {
        List<Threads> threadsList = threadsMapper.queryHotArticles(type,categoryId);
        if (threadsList == null) {
            return null;
        }
        List<ArticlesAndTopicsVO> list = getArticleVOList(threadsList);
        return list;
    }

    @Override
    @Transactional
    public List<ArticlesAndTopicsVO> latestArticle(Long categoryId,Integer type) {
        List<Threads> threadsList = threadsMapper.latestArticle(type,categoryId);
        if (threadsList == null) {
            return null;
        }
        List<ArticlesAndTopicsVO> list = getArticleVOList(threadsList);
        return list;
    }

    @Override
    @Transactional
    public List<MyThreadsVO> myThreads(Long userId) {
        List<Threads> threadsList = threadsMapper.queryByUserId(userId);
        List<MyThreadsVO> list = threadsList.stream().map(thread -> {
            MyThreadsVO myThreadsVO = new MyThreadsVO();
            BeanUtils.copyProperties(thread, myThreadsVO);
            Long threadId = thread.getId();
            List<Images> images = imagesMapper.queryByThreadId(threadId);
            myThreadsVO.setImageList(images);
            return myThreadsVO;
        }).toList();
        return list;
    }


    private List<ArticlesAndTopicsVO> getArticleVOList(List<Threads> threadsList) {
        List<ArticlesAndTopicsVO> list = threadsList.stream().map(thread -> {
            ArticlesAndTopicsVO articlesAndTopicsVO = new ArticlesAndTopicsVO();
            BeanUtils.copyProperties(thread, articlesAndTopicsVO);

            Long threadId = thread.getId();
            String image = imagesMapper.queryByIdImage(threadId);
            articlesAndTopicsVO.setImage(image);
            UserInfoVO userInfoVO = userMapper.getUserInfoById(thread.getUserId());
            BeanUtils.copyProperties(userInfoVO, articlesAndTopicsVO);
            return articlesAndTopicsVO;
        }).toList();
        return list;
    }

}
